<template>
    <el-row :gutter="30">
        <el-card style="margin:0 0 20px 0px">
            <el-row class="form-row">
                <el-form label-position="right" :rules="rules" :model="filter" label-width="90px" inline>
                    <el-form-item label="上级机构">
                        <treeselect :options="optionsDepart" noChildrenText="没有子节点" noOptionsText="暂无选项"
                                    noResultsText="没有发现结果" :default-expand-level="1" :value="value"
                                    placeholder="选择上级机构" style="width: 250px"
                                    :show-count="true" v-model="filter.treeid"/>
                    </el-form-item>
                    <el-form-item label="姓名">
                        <div class="filters-input">
                            <el-input placeholder="姓名" v-model="filter.name" size="large"/>
                        </div>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" icon="md-search" size="large" @click="loadData()">
                            搜索
                        </el-button>
                    </el-form-item>
                </el-form>
                <el-button type="primary" icon="md-add" size="large" @click="handleAdd('新增')">
                    新增
                </el-button>
            </el-row>

            <el-table stripe border :data="tableData" size="large" ref="table">
                <template slot="empty">暂无数据</template>
                <el-table-column prop="name" label="姓名"></el-table-column>
                <el-table-column prop="phone" label="登录账号/电话"></el-table-column>
                <el-table-column prop="roleName" label="用户权限"></el-table-column>
                <el-table-column prop="deptName" label="物业"></el-table-column>
                <el-table-column prop="housingName" label="小区"></el-table-column>
                <el-table-column label="账户状态" align="center">
                    <!-- 数据库1是启用，-1是禁用 -->
                    <template slot-scope="scope">
                        <el-switch v-model="scope.row.status" active-text="开启" inactive-text="禁用"
                                   @change="switchChange(scope.$index, scope.row)"
                                   :change="logchange(scope.$index, scope.row)"></el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="150" align="center">
                    <template slot-scope="scope">
                        <el-button size="mini" type="primary" @click="handleAdd('修改',scope.row)">修改</el-button>
                        <el-button size="mini" type="danger" @click="handleDelete(scope.row.id)">删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <Page style="margin: 10px 0;" :total="pageTotal" :current="pageNum" :page-size="pageSize" show-total
                  show-sizer show-elevator @on-change="handlePage" @on-page-size-change='handlePageSize'>
            </Page>
        </el-card>

        <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="formVisible" :mask-closable="false"
                   :closable="false" width="900px">
            <el-form :model="user" :rules="rules" ref="form2" label-position="right" label-width="110px"
                     class="myOpenFrom">
                <el-form-item label="物业" prop="deptId">
                    <treeselect :options="optionsParent" :default-expand-level="1" @input="propertyChange"
                                :disable-branch-nodes="true" :disabled="this.title=='修改'?true:false"
                                noChildrenText="没有子节点" noOptionsText="暂无选项"
                                noResultsText="没有发现结果" :value="value" placeholder="选择物业" v-model="user.deptId"/>
                </el-form-item>
                <el-form-item label="用户" prop="user_name">
                    <el-input type="text" v-model="user_name" :disabled="this.title=='修改'?true:false"
                              placeholder="请输入用户"></el-input>
                    <span v-if="this.title=='修改'?false:true" @click="alertMemberDialog"
                          style="color: blue">从通讯录选择用户</span>
                </el-form-item>
                <el-form-item label="登录账号/电话" prop="phone">
                    <el-input v-model="user.phone" onkeyup="value=value.replace(/[^\d]/g,'')"maxlength="11"
                              placeholder="登录账号/电话"></el-input>
                </el-form-item>
                <el-form-item label="登录密码" prop="password" v-if="this.title=='修改'?false:true">
                    <el-input type="password" v-model="user.password" placeholder="登录密码" size="large"
                              required="true"></el-input>
                </el-form-item>
                <el-form-item label="分配角色" prop="roleIdList">
                    <treeselect :options="roleTreeList" multiple :disable-branch-nodes="true" noChildrenText="没有子节点"
                                noOptionsText="暂无选项" noResultsText="没有发现结果" :value="value" placeholder="选择角色"
                                v-model="user.roleIdList"/>
                </el-form-item>
                <el-form-item label="小区" prop="houseList">
                    <el-transfer :titles="['未选小区', '已选小区']" :button-texts="['取消小区', '选择小区']" v-model="user.houseList"
                                 :data="housingList" :props="{key: 'id',label: 'name'}"></el-transfer>
                </el-form-item>
            </el-form>

            <div slot="footer">
                <el-button type="text" size="large" @click="formVisible = false">取消</el-button>
                <el-button type="primary" size="large" @click="handleSubmit('form2')" :loading="formLoading">确定
                </el-button>
            </div>
        </el-dialog>
        <!--人员选择插件-->
        <MemberSelector :data-tree="treeList" mode="SingleMember" :data-member="nameList" ref="memberSelector"
                        @treenodeclick="treeNodeClick" @affirmative="confirmMember">
        </MemberSelector>
    </el-row>
</template>
<script>
    import Treeselect from "@riophae/vue-treeselect";
    import MemberSelector from "../../components/member-selector/selector"

    //点击触发,首先点击parent1-1,获取id,然后会调用post,把id传过去获取到tableData和pageTolal到table和page
    export default {
        name: "userList",
        components: {
            MemberSelector,
            Treeselect,
        },
        data() {
            return {
                //校验规则
                rules: {
                    deptId: [
                        {
                            required: true,
                            message: "请选择物业"
                        }
                    ],
                    name: [
                        {
                            required: true,
                            message: "姓名不能为空"
                        }
                    ],
                    password: [
                        {required: true, message: "密码不能为空"},
                        {min: 6, message: "最少6位密码"}
                    ],
                    roleIdList: [
                        {
                            required: true,
                            message: "请选择权限",
                        }
                    ],
                    phone: [
                        {required: true, message: "登录账号或电话不能为空"},
                        {min: 11, max: 11, message: "请输入11位手机号"}
                    ],
                    houseList: [
                        {
                            required: true,
                            message: "请选择管理小区",
                        }
                    ]
                },
                title: "",
                //权限角色
                roleList: [],
                roleTreeList: [],
                //用户
                nameList: [],
                //部门
                treeList: [],
                //小区
                housingList: [],
                //新增修改选择物业
                optionsParent: [],
                value: null,
                //查询条件
                filter: {},
                optionsDepart: [],
                //页码
                pageNum: 1,
                //每页数量
                pageSize: 10,
                //总数
                pageTotal: 0,
                //对话框隐藏状态
                formVisible: false,
                user: {
                    deptId: "",
                    wyUserId:"",
                    name: "",
                    phone: "",
                    password: "",
                    houseList: [],
                    roleIdList: [],
                },
                user_name:"",
                //表单提交状态
                formLoading: false,
                tableData: [],
            };
        },

        created: function () {
            this.loadDepart();
            this.loadData();
        },
        methods: {
            //加载数据
            loadData() {
                const params = this.filter;
                params.deptId = this.filter.treeid;
                params.name = this.filter.name;
                params.pageNum = this.pageNum;
                params.pageSize = this.pageSize;
                //与后台交换数据
                this.postRequest("/api/user/loadData", params).then(res => {
                    console.log(res)
                    if (res.code == 20000) {
                        this.tableData = res.data.list;
                        this.pageTotal = res.data.total;
                    } else {
                        this.tableData = [];
                        this.$Message.error({
                            content: res.message,
                            duration: 5
                        });
                    }
                });
            },
            //加载角色树
            roleTree(deptId) {
                this.getRequest("/api/manageHR/getRoleTree?deptId=" + deptId).then(res => {
                    if (res.code == 20000) {
                        this.roleTreeList = res.data;
                    } else {
                        this.$Message.error({
                            content: res.message,
                            duration: 5
                        });
                    }
                });
            },
            //选择物业
            propertyChange() {
                if (this.user.deptId) {
                    let params = {};
                    params.parentId = this.user.deptId;
                    this.postRequest("/api/user/housingByPorpertId", params).then(res => {
                        console.log(res.data);
                        this.housingList = res.data;
                    });
                    this.treeData(this.user.deptId)
                    this.roleTree(this.user.deptId);
                }
            },
            //加载部门树
            treeData(companyId) {
                this.getRequest("/api/manageHR/getCompanyByPropertyId?id=" + companyId).then(res => {
                    console.log(res);
                    if (res.code == 20000) {
                        this.treeList = res.data;
                    } else {
                        this.$Message.error({
                            content: res.message,
                            duration: 5
                        });
                    }
                });
            },
            //弹出部门人员选择框
            alertMemberDialog: function () {
                this.$refs.memberSelector.showDialog();
            },
            //部门点击选择
            treeNodeClick: function (data) {
                const params = {};
                params.pageNum = null;
                params.companyId = data.companyId;
                //与后台交换数据
                this.postRequest("/api/manageHR/getUserByCompany", params).then(res => {
                    if (res.code == 20000) {
                        const _this = this;
                        const tmpList = [];
                        res.data.forEach(function (c) {
                            const list = c;
                            list.label = (c.name);
                            tmpList.push(list);
                        });
                        this.nameList = tmpList;
                    } else {
                        this.$Message.error({
                            content: res.message,
                            duration: 5
                        });
                    }
                });
            },
            //确认选择人员
            confirmMember(data) {
                this.user.wyUserId = data[0].id;
                this.user_name = data[0].name;
            },
            //打开新增修改页面
            handleAdd(title, row) {
                this.treeList = [];
                this.nameList = [];
                this.user = {
                    houseList: [],
                };
                this.user_name = "";
                this.title = title;
                if (title == '修改') {
                    this.user = row;
                    this.user_name = row.name;
                    this.propertyChange();
                }
                this.formVisible = true;
            },
            //保存
            handleSubmit(form2) {
                this.$refs[form2].validate(valid => {
                    if (valid) {
                        if(!this.user_name){
                            this.$message.error("请输入用户名");
                            return;
                        }
                        this.formLoading = true;
                        if (this.user.status) {
                            this.user.status = 1;
                        } else {
                            this.user.status = -1;
                        }
                        this.user.name = this.user_name;
                        //修改时，不修改密码
                        if (this.title == '修改') {
                            this.user.password = null;
                        }
                        this.postRequest("/api/user/saveOrUpdate", this.user).then(res => {
                            if (res.code == 20000) {
                                this.formLoading = false;
                                this.formVisible = false;
                                this.$Message.success("保存成功");
                                this.loadData();
                            } else {
                                this.formLoading = false;
                                this.$message.error(res.message);
                            }
                        });
                    }
                });
            },
            //加载物业
            loadDepart() {
                this.postRequest("/api/user/treeList").then(res => {
                    if (res.code == 20000) {
                        this.optionsDepart = res.data;
                        this.optionsParent = res.data
                    } else {
                        this.$Message.error({
                            content: res.message,
                            duration: 5
                        });
                    }
                });
            },
            //删除
            handleDelete: function (id) {
                this.$Modal.confirm({
                    title: "提示",
                    content: "确定删除该条记录？",
                    onOk: () => {
                        this.getRequest("/api/user/deleteById?id=" + id).then(res => {
                            this.tableLoading = false;
                            if (res.code == 20000) {
                                this.$Message.success("删除成功!");
                                this.pageNum = 1;
                                this.loadData();
                            } else {
                                this.$Message.error({
                                    content: res.message,
                                    duration: 5
                                });
                            }
                        });
                    },
                });
            },
            //更改账户状态
            switchChange: function (index, row) {
                if (row.status) {
                    status = 1;
                } else {
                    status = -1;
                }
                let params = {};
                params.id = row.id;
                params.status = status;
                console.log(params);
                this.postRequest("/api/user/updateByStatus", params).then(res => {
                    if (res.code == 20000) {
                        this.loadData();
                        this.$Message.success("权限修改成功！");
                    } else {
                        this.$Message.error({
                            content: res.message,
                            duration: 5
                        });
                    }
                });
            },
            //账户状态
            logchange: function (index, row) {
                if (row.status == 1) {
                    row.status = true;
                } else if (row.state == "-1") {
                    row.status = false;
                }
            },
            handlePage(value) {
                this.pageNum = value;
                this.loadData();
            },
            handlePageSize(value) {
                this.pageSize = value;
                this.loadData();
            },
        }
    };
</script>
